<!--
  智慧社区管理系统 - 角色管理列表
  @author Wu.Liang
  @date 2024-01-01
  @updated 2024-12-21 - 按UI设计优化角色管理页面
  @updated 2025-06-28 - 完善真实API调用，移除模拟数据
  @updated 2025-07-22 - 删除导出Excel功能，移除分页，展示所有角色
-->
<template>
    <div class="role-list">
        <!-- 页面标题和描述 -->
        <div class="page-header">
            <div class="page-title">
                <h1>角色管理</h1>
                <p class="page-desc">管理系统预设角色信息，包括权限分配、状态管理等（角色由系统预设，不允许手动创建）</p>
            </div>
            <div class="page-actions">
                <!-- 新增角色功能已移除 - 角色由系统预设，不允许手动创建 -->
            </div>
        </div>

        <!-- 搜索和筛选区域 -->
        <el-card class="search-card">
            <el-form :model="searchForm" :inline="true" class="search-form" label-width="80px">
                <el-form-item label="角色名称">
                    <el-input 
                        v-model="searchForm.roleName" 
                        placeholder="请输入角色名称" 
                        clearable 
                        style="width: 200px"
                        @keyup.enter="handleSearch"
                        :prefix-icon="User"
                    />
                </el-form-item>
                <el-form-item label="角色编码">
                    <el-input 
                        v-model="searchForm.roleCode" 
                        placeholder="请输入角色编码" 
                        clearable 
                        style="width: 200px"
                        @keyup.enter="handleSearch"
                        :prefix-icon="Key"
                    />
                </el-form-item>
                <el-form-item label="状态">
                    <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 120px">
                        <el-option :label="STATUS.ENABLED" :value="1" />
                        <el-option :label="STATUS.DISABLED" :value="0" />
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" :icon="Search" @click="handleSearch">
                        搜索
                    </el-button>
                    <el-button :icon="Refresh" @click="handleReset">
                        重置
                    </el-button>
                </el-form-item>
            </el-form>
        </el-card>

        <!-- 批量操作区域 -->
        <div class="batch-actions" v-if="multipleSelection?.length > 0">
            <el-alert 
                :title="`已选择 ${multipleSelection?.length} 项`" 
                type="info" 
                :closable="false"
                show-icon
            >
                <template #default>
                    <el-button type="primary" size="small" @click="handleBatchEnable">
                        批量启用
                    </el-button>
                    <el-button type="warning" size="small" @click="handleBatchDisable">
                        批量禁用
                    </el-button>
                    <el-button type="danger" size="small" @click="handleBatchDelete">
                        批量删除
                    </el-button>
                    <el-button size="small" @click="clearSelection">
                        取消选择
                    </el-button>
                </template>
            </el-alert>
        </div>

        <!-- 角色列表卡片区域 -->
        <div class="role-cards" v-loading="loading">
            <el-row :gutter="20">
                <el-col 
                    v-for="role in tableData" 
                    :key="role.id" 
                    :xs="24" 
                    :sm="12" 
                    :md="8" 
                    :lg="6"
                >
                    <el-card class="role-card" shadow="hover">
                        <div class="role-header">
                            <div class="role-info">
                                <h3 class="role-name">{{ role.roleName }}</h3>
                                <p class="role-code">{{ role.roleCode }}</p>
                            </div>
                            <div class="role-status">
                                <el-tag :type="getStatusTagType(role.status)" size="small">
                                    {{ getStatusText(role.status) }}
                                </el-tag>
                            </div>
                        </div>
                        
                        <div class="role-description">
                            <p>{{ role.description || '暂无描述' }}</p>
                        </div>
                        
                        <div class="role-meta">
                            <div class="meta-item">
                                <el-icon><Calendar /></el-icon>
                                <span>创建时间：{{ formatDate(role.createTime) }}</span>
                            </div>
                            <div class="meta-item">
                                <el-icon><Sort /></el-icon>
                                <span>排序：{{ role.sortOrder }}</span>
                            </div>
                            <div class="meta-item" v-if="role.roleType">
                                <el-icon><User /></el-icon>
                                <span>类型：{{ getRoleTypeText(role.roleType) }}</span>
                            </div>
                        </div>
                        
                        <div class="role-actions">
                            <el-button 
                                type="primary" 
                                size="small" 
                                :icon="Setting"
                                @click="handleAssignPermission(role)"
                            >
                                分配权限
                            </el-button>
                            <el-button 
                                type="primary" 
                                link 
                                :icon="View" 
                                @click="handleView(role)"
                            >
                                查看
                            </el-button>
                            <el-button 
                                type="primary" 
                                link 
                                :icon="Edit" 
                                @click="handleEdit(role)"
                                :disabled="role.isSystem === 1"
                            >
                                编辑
                            </el-button>
                            <el-dropdown @command="(command) => handleCommand(command, role)">
                                <el-button type="primary" link>
                                    更多<el-icon class="el-icon--right"><ArrowDown /></el-icon>
                                </el-button>
                                <template #dropdown>
                                    <el-dropdown-menu>
                                        <el-dropdown-item 
                                            command="status" 
                                            :disabled="role.isSystem === 1"
                                        >
                                            {{ role.status === 1 ? '禁用' : '启用' }}
                                        </el-dropdown-item>
                                        <el-dropdown-item 
                                            command="delete" 
                                            :disabled="role.isSystem === 1"
                                        >
                                            删除
                                        </el-dropdown-item>
                                    </el-dropdown-menu>
                                </template>
                            </el-dropdown>
                        </div>
                    </el-card>
                </el-col>
            </el-row>
            
            <!-- 空状态 -->
            <el-empty 
                v-if="!loading && tableData?.length === 0" 
                description="暂无角色数据"
                :image-size="200"
            >
                <!-- 新增角色功能已移除 -->
            </el-empty>
        </div>

        <!-- 角色表单弹窗已移除 - 角色由系统预设，不允许手动创建 -->

        <!-- 权限分配弹窗 -->
        <PermissionAssignDialog 
            v-model="permissionDialogVisible"
            :role-data="currentRole"
            @success="handlePermissionSuccess"
        />

        <!-- 角色详情弹窗 -->
        <RoleDetailDialog 
            v-model="detailDialogVisible"
            :role-data="currentRole"
        />
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessageBox } from 'element-plus'
import { STATUS } from '@/constants/status'
import { showMessage } from '@/utils/message'
import { 
    Plus, 
    Search, 
    Refresh, 
    View, 
    Edit, 
    Setting,
    ArrowDown,
    User,
    Key,
    Calendar,
    Sort
} from '@element-plus/icons-vue'
import type { RoleInfo, RoleListParams } from '@/api/role'
import { 
    getRoleList, 
    deleteRole, 
    batchDeleteRoles,
    updateRole,
    getRoleDetail // 新增获取角色详情的API
} from '@/api/role'
import PermissionAssignDialog from './components/PermissionAssignDialog.vue'
import RoleDetailDialog from './components/RoleDetailDialog.vue'
import PermissionGuard from '@/components/PermissionGuard.vue'

// 响应式数据
const loading = ref(false)
const tableData = ref<RoleInfo[]>([])
const multipleSelection = ref<RoleInfo[]>([])

// 弹窗控制
const permissionDialogVisible = ref(false)
const detailDialogVisible = ref(false)
const formDialogVisible = ref(false) // 添加缺失的变量定义
const currentRole = ref<RoleInfo | null>(null)

// 搜索表单
const searchForm = reactive<RoleListParams>({
    current: 1,
    size: 9999, // 设置一个很大的值来获取所有角色
    roleName: '',
    roleCode: '',
    status: undefined as number | undefined
})

// 获取角色列表
const fetchRoleList = async () => {
    try {
        loading.value = true
        const params: RoleListParams = {
            current: 1,
            size: 9999, // 获取所有角色
            roleName: searchForm.roleName || undefined,
            roleCode: searchForm.roleCode || undefined,
            status: searchForm.status
        }
        
        const { data } = await getRoleList(params)
        if (data && data.records) {
            tableData.value = data.records
        } else {
            tableData.value = []
        }
    } catch (error: any) {
        console.error('获取角色列表失败:', error)
        showMessage({ type: 'error', message: `获取角色列表失败: ${error.message || '网络错误'}` })
        tableData.value = []
    } finally {
        loading.value = false
    }
}

// 搜索处理
const handleSearch = () => {
    fetchRoleList()
}

// 重置搜索
const handleReset = () => {
    Object.assign(searchForm, {
        current: 1,
        size: 9999,
        roleName: '',
        roleCode: '',
        status: undefined as number | undefined
    })
    fetchRoleList()
}

// 选择处理
const handleSelectionChange = (selection: RoleInfo[]) => {
    multipleSelection.value = selection
}

const clearSelection = () => {
    multipleSelection.value = []
}

// 新增角色功能已移除
// const handleAdd = () => {
//     currentRole.value = null
//     formDialogVisible.value = true
// }

// 编辑角色
const handleEdit = async (role: RoleInfo) => {
  try {
    // 先获取完整的角色详情数据
    const response = await getRoleDetail(role.id)
    if (response.data) {
      currentRole.value = response.data
    } else {
      // 如果获取详情失败，使用列表数据
      currentRole.value = { ...role }
    }
    formDialogVisible.value = true
  } catch (error) {
    console.error('获取角色详情失败:', error)
    // 获取详情失败时，使用列表数据
    currentRole.value = { ...role }
    formDialogVisible.value = true
  }
}

// 查看角色详情
const handleView = (role: RoleInfo) => {
    currentRole.value = { ...role }
    detailDialogVisible.value = true
}

// 分配权限
const handleAssignPermission = (role: RoleInfo) => {
    currentRole.value = { ...role }
    permissionDialogVisible.value = true
}

// 删除角色
const handleDelete = async (role: RoleInfo) => {
    try {
        await ElMessageBox.confirm(
            `确定要删除角色"${role.roleName}"吗？删除后不可恢复。`,
            '确认删除',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        )
        
        await deleteRole(role.id)
        showMessage({ type: 'success', message: '删除成功' })
        fetchRoleList()
    } catch (error: any) {
        if (error !== 'cancel') {
            showMessage({ type: 'error', message: `删除失败: ${error.message || '网络错误'}` })
        }
    }
}

// 批量操作
const handleBatchEnable = async () => {
    try {
        await ElMessageBox.confirm(
            `确定要启用选中的 ${multipleSelection.value.length} 个角色吗？`,
            '确认批量启用',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        )
        
        const promises = multipleSelection.value.map(role => 
            updateRole(role.id, { status: 0 })
        )
        await Promise.all(promises)
        showMessage({ type: 'success', message: '批量启用成功' })
        clearSelection()
        fetchRoleList()
    } catch (error: any) {
        if (error !== 'cancel') {
            showMessage({ type: 'error', message: `批量启用失败: ${error.message || '网络错误'}` })
        }
    }
}

const handleBatchDisable = async () => {
    try {
        await ElMessageBox.confirm(
            `确定要禁用选中的 ${multipleSelection.value.length} 个角色吗？`,
            '确认批量禁用',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        )
        
        const promises = multipleSelection.value.map(role => 
            updateRole(role.id, { status: 1 })
        )
        await Promise.all(promises)
        showMessage({ type: 'success', message: '批量禁用成功' })
        clearSelection()
        fetchRoleList()
    } catch (error: any) {
        if (error !== 'cancel') {
            showMessage({ type: 'error', message: `批量禁用失败: ${error.message || '网络错误'}` })
        }
    }
}

const handleBatchDelete = async () => {
    try {
        await ElMessageBox.confirm(
            `确定要删除选中的 ${multipleSelection.value.length} 个角色吗？删除后不可恢复。`,
            '确认批量删除',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        )
        
        const ids = multipleSelection.value.map(role => role.id)
        await batchDeleteRoles(ids)
        showMessage({ type: 'success', message: '批量删除成功' })
        clearSelection()
        fetchRoleList()
    } catch (error: any) {
        if (error !== 'cancel') {
            showMessage({ type: 'error', message: `批量删除失败: ${error.message || '网络错误'}` })
        }
    }
}

// 下拉菜单命令处理
const handleCommand = (command: string, role: RoleInfo) => {
    switch (command) {
        case 'status':
            handleToggleStatus(role)
            break
        case 'delete':
            handleDelete(role)
            break
    }
}

// 切换状态
const handleToggleStatus = async (role: RoleInfo) => {
    try {
        const newStatus = role.status === 0 ? 1 : 0
        const statusText = newStatus === 1 ? '启用' : '禁用'
        
        await ElMessageBox.confirm(
            `确定要${statusText}角色"${role.roleName}"吗？`,
            `确认${statusText}`,
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        )
        
        await updateRole(role.id, { status: newStatus })
        showMessage({ type: 'success', message: `${statusText}成功` })
        fetchRoleList()
    } catch (error: any) {
        if (error !== 'cancel') {
            showMessage({ type: 'error', message: `操作失败: ${error.message || '网络错误'}` })
        }
    }
}

// 表单成功回调已移除
// const handleFormSuccess = () => {
//     formDialogVisible.value = false
//     fetchRoleList()
// }

// 权限分配成功回调
const handlePermissionSuccess = () => {
    permissionDialogVisible.value = false
    showMessage({ type: 'success', message: '权限分配成功' })
}

// 工具函数
const getStatusTagType = (status: number) => {
    return status === 1 ? 'success' : 'danger'
}

const getStatusText = (status: number) => {
    return status === 1 ? '启用' : '禁用'
}

const getRoleTypeText = (roleType: number) => {
    return roleType === 1 ? '系统角色' : '自定义角色'
}

const formatDate = (date: string) => {
    if (!date) return '-'
    return new Date(date).toLocaleString('zh-CN')
}

// 初始化
onMounted(() => {
    fetchRoleList()
})
</script>

<style lang="scss" scoped>
.role-list {
    padding: 20px;
    background-color: #f5f7fa;
    min-height: calc(100vh - 120px);

    .page-header {
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
        margin-bottom: 20px;
        padding: 20px;
        background: white;
        border-radius: 8px;
        box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);

        .page-title {
            h1 {
                margin: 0 0 8px 0;
                font-size: 24px;
                font-weight: 600;
                color: #303133;
            }

            .page-desc {
                margin: 0;
                color: #909399;
                font-size: 14px;
            }
        }

        .page-actions {
            display: flex;
            gap: 12px;
        }
    }

    .search-card {
        margin-bottom: 20px;
        border-radius: 8px;

        .search-form {
            .el-form-item {
                margin-bottom: 16px;
            }
        }
    }

    .batch-actions {
        margin-bottom: 20px;

        .el-alert {
            border-radius: 8px;

            .el-alert__content {
                display: flex;
                align-items: center;
                gap: 12px;
            }
        }
    }

    .role-cards {
        margin-bottom: 20px;

        .role-card {
            margin-bottom: 20px;
            border-radius: 8px;
            transition: all 0.3s ease;

            &:hover {
                transform: translateY(-2px);
                box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
            }

            .role-header {
                display: flex;
                justify-content: space-between;
                align-items: flex-start;
                margin-bottom: 12px;

                .role-info {
                    flex: 1;

                    .role-name {
                        margin: 0 0 4px 0;
                        font-size: 16px;
                        font-weight: 600;
                        color: #303133;
                    }

                    .role-code {
                        margin: 0;
                        font-size: 12px;
                        color: #909399;
                        font-family: 'Courier New', monospace;
                    }
                }

                .role-status {
                    flex-shrink: 0;
                }
            }

            .role-description {
                margin-bottom: 12px;
                min-height: 40px;

                p {
                    margin: 0;
                    font-size: 14px;
                    color: #606266;
                    line-height: 1.5;
                    display: -webkit-box;
                    -webkit-line-clamp: 2;
                    -webkit-box-orient: vertical;
                    overflow: hidden;
                }
            }

            .role-meta {
                margin-bottom: 16px;

                .meta-item {
                    display: flex;
                    align-items: center;
                    gap: 6px;
                    margin-bottom: 6px;
                    font-size: 12px;
                    color: #909399;

                    .el-icon {
                        font-size: 14px;
                    }
                }
            }

            .role-actions {
                display: flex;
                align-items: center;
                gap: 8px;
                padding-top: 12px;
                border-top: 1px solid #f0f0f0;
            }
        }
    }
}

// 响应式设计
@media (max-width: 768px) {
    .role-list {
        padding: 10px;

        .page-header {
            flex-direction: column;
            gap: 16px;

            .page-actions {
                width: 100%;
                justify-content: flex-end;
            }
        }

        .role-cards {
            .el-col {
                margin-bottom: 16px;
            }
        }
    }
}
</style>
